/*
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package jsr203.sun.nio.fs;

import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import jsr203.nio.file.FileStore;
import jsr203.nio.file.FileSystem;
import jsr203.nio.file.NameMatcher;
import jsr203.nio.file.Path;
import jsr203.nio.file.ProviderMismatchException;
import jsr203.nio.file.attribute.BasicFileAttributeView;
import jsr203.nio.file.attribute.FileAttributeView;
import jsr203.nio.file.attribute.FileOwnerAttributeView;
import jsr203.nio.file.attribute.PosixFileAttributeView;
import jsr203.nio.file.spi.FileSystemProvider;
import sun.security.action.GetBooleanAction;

/**
 * Base implementation of FileSystem for Unix-like implementations.
 */

abstract class UnixFileSystem
    extends FileSystem
{
    private final UnixFileSystemProvider provider;
    private final byte[] defaultDirectory;
    private final UnixPath rootDirectory;
    private final boolean chdirAllowed;

    // package-private
    UnixFileSystem(UnixFileSystemProvider provider, String dir) {
        this.provider = provider;
        this.defaultDirectory = UnixPath.normalizeAndCheck(dir).getBytes();
        if (this.defaultDirectory[0] != '/') {
            throw new RuntimeException("default directory must be absolute");
        }
        this.rootDirectory = new UnixPath(this, "/");

        // system property indicates if process-wide chdir is allowed. If so
        // then access to the file system is via absolute paths.
        PrivilegedAction<Boolean> pa = new GetBooleanAction("sun.nio.fs.chdirAllowed");
        this.chdirAllowed = AccessController.doPrivileged(pa).booleanValue();
    }

    // package-private
    byte[] defaultDirectory() {
        return defaultDirectory;
    }

    UnixPath rootDirectory() {
        return rootDirectory;
    }

    boolean chdirAllowed() {
        return chdirAllowed;
    }

    boolean isSolaris() {
        return false;
    }

    @Override
    public final FileSystemProvider provider() {
        return provider;
    }

    @Override
    public final String getSeparator() {
        return "/";
    }

    @Override
    public final boolean isOpen() {
        return true;
    }

    @Override
    public final boolean isReadOnly() {
        return false;
    }

    @Override
    public final void close() throws IOException {
        // nothing to do
    }

    /**
     * Copies extended attributes from the source to target file.
     *
     * @param   sfd
     *          Open file descriptor to source file
     * @param   tfd
     *          Open file descriptor to target file
     */
    abstract void copyExtendedAttributes(int sfd, int tfd);

    /**
     * Tells if directory relative system calls (openat, etc.) are available
     * on this operating system.
     */
    abstract boolean supportsSecureDirectoryStreams();

    /**
     * Unix systems only have a single root directory (/)
     */
    @Override
    public final Iterable<Path> getRootDirectories() {
        try {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null)
                sm.checkRead(rootDirectory.toString());
            return Arrays.asList((Path)rootDirectory);
        } catch (SecurityException x) {
            return Collections.emptyList();
        }
    }

    /**
     * Returns object to iterate over entries in mounttab or equivalent
     */
    abstract Iterable<UnixMountEntry> getMountEntries();

    /**
     * Returns a FileStore to represent the file system where the given file
     * reside.
     */
    abstract FileStore getFileStore(UnixPath path) throws IOException;

    /**
     * Returns a FileStore to represent the file system for the given mount
     * mount.
     */
    abstract FileStore getFileStore(UnixMountEntry entry);

    /**
     * Iterator returned by getFileStores method.
     */
    private class FileStoreIterator implements Iterator<FileStore> {
        private final Iterator<UnixMountEntry> entries;
        private FileStore next;

        FileStoreIterator(Iterator<UnixMountEntry> entries) {
            this.entries = entries;
            this.next = null;
        }

        private FileStore readNext() {
            assert Thread.holdsLock(this);
            for (;;) {
                if (!entries.hasNext())
                    return null;
                UnixMountEntry entry = entries.next();

                // skip entries with the "ignore" option
                if (entry.isIgnored())
                    continue;

                // check permission to read mount point
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    try {
                        sm.checkRead(new String(entry.dir()));
                    } catch (SecurityException x) {
                        continue;
                    }
                }
                return getFileStore(entry);
            }
        }

        @Override
        public synchronized boolean hasNext() {
            if (next != null)
                return true;
            next = readNext();
            return next != null;
        }

        @Override
        public synchronized FileStore next() {
            if (next == null)
                next = readNext();
            if (next == null) {
                throw new NoSuchElementException();
            } else {
                FileStore result = next;
                next = null;
                return result;
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    @Override
    public final Iterable<FileStore> getFileStores() {
        Iterator<UnixMountEntry> entries = getMountEntries().iterator();

        final FileStoreIterator iterator = new FileStoreIterator(entries);
        return new Iterable<FileStore>() {
            public Iterator<FileStore> iterator() {
                return iterator;
            }
        };
    }

    @Override
    public final UnixPath getPath(String path) {
        return new UnixPath(this, path);
    }

    @Override
    public NameMatcher getNameMatcher(String syntaxAndPattern) {
        String syntax = GLOB_SYNTAX;
        String expr = "";

        int pos = syntaxAndPattern.indexOf(':');
        if (pos == -1) {
            expr = syntaxAndPattern;
        } else {
            syntax = syntaxAndPattern.substring(0, pos++);
            if (pos == syntaxAndPattern.length())
                throw new PatternSyntaxException("Pattern is empty", syntaxAndPattern, pos);
            expr = syntaxAndPattern.substring(pos);
        }

        if (syntax.equalsIgnoreCase(GLOB_SYNTAX)) {
            expr = Globs.toRegexPattern(expr);
        } else {
            if (!syntax.equalsIgnoreCase(REGEX_SYNTAX)) {
                throw new ProviderMismatchException("Syntax '" + syntax +
                    "' not recognized");
            }
        }

        // return matcher
        final Pattern pattern = Pattern.compile(expr);
        return new NameMatcher() {
            @Override
            public boolean match(Path name) {
                if (name.getParent() != null)
                    throw new IllegalArgumentException("Name has parent component");
                return pattern.matcher(name.toString()).matches();
            }
        };
    }
    private static final String GLOB_SYNTAX = "glob";
    private static final String REGEX_SYNTAX = "regex";

    @Override
    @SuppressWarnings("unchecked")
    public Iterable<Class<? extends FileAttributeView>> getFileAttributeViews() {
        ArrayList list = new ArrayList();
        list.add(BasicFileAttributeView.class);
        list.add(PosixFileAttributeView.class);
        list.add(FileOwnerAttributeView.class);
        return list;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <V extends FileAttributeView> V newFileAttributeView(Class<V> view)
    {
        if (view == null)
            throw new NullPointerException();
        Class<?> c = view;
        if (c == BasicFileAttributeView.class)
            return (V) UnixFileAttributeView.createBasicView();
        if (c == PosixFileAttributeView.class)
            return (V) UnixFileAttributeView.createPosixView();
        if (c == FileOwnerAttributeView.class)
            return (V) UnixFileAttributeView.createOwnerView();
        return (V) null;
    }
}
